import { routerRedux } from 'dva/router';
import { message, Modal } from 'antd';
import { getStorage, getUserInfo, removeStorage, setStorage } from '/common/utils/utils';
import { isLogin } from '@/helpers/request';
import router from 'umi/router';
import isArray from 'lodash/isArray';
import isEmpty from 'lodash/isEmpty';
import isObject from 'lodash/isObject';
import omit from 'lodash/omit';
import orderBy from 'lodash/orderBy';
import isFunction from 'lodash/isFunction';
import {
  findByCode,
  findByAppCode,
  findIndustry,
  findSolution,
  resetPassword,
  logout,
  findByFinderCode,
  findDocList,
  renameDoc,
  deleteDoc,
  createDoc,
  uploadDoc,
  batchDelDoc,
  sendCaptcha, findUserInfo, findObjectList,
} from '@/services/global';

const userInfo = getStorage('userInfo') || {};

export default {
  namespace: 'global',
  state: {
    appCode: '', // 当前应用的 appCode
    loginTimeout: false, // 标识是否登录会话过期了
    userInfo: userInfo,
    collapsed: false,
    siderWidth: 200,
    industry: [], //行业类型
    solution: [], //解决方案
    docList: [], //文档信息
  },

  effects: {
    * findByCode({ payload }, { put }) {
      return yield put({
        type: 'findByCodeFunc',
        payload,
      });
    },
    * findByAppCode({ payload }, { put }) {
      return yield put({
        type: 'findByCodeFunc',
        payload,
      });
    },
    * findByFinderCode({ payload }, { put }) {
      return yield put({
        type: 'findByCodeFunc',
        payload,
      });
    },
    * findByCodeFunc({ payload }, { call, put, select }) {
      let code = payload.appCode ? payload.appCode :
        payload.finderCode ? payload.finderCode : payload.code;
      if (code) {
        if (payload.code) {
          // 如果该枚举数据已有值，则不再请求
          const comboList = yield select(state => state['global'][code]);
          if (!isEmpty(comboList)) return {
            status: 200,
            data: comboList,
          };
        }
        const response = yield call(
          payload.appCode ? findByAppCode :
            payload.finderCode ? findByFinderCode : findByCode,
          payload);
        if (typeof response != 'undefined' &&
          (200 === response.status || 1 === response.status)) {
          yield put({
            type: 'changeComboData',
            payload: {
              code,
              data: response.data,
            },
          });
          return response;
        }
      }
    },
    /**
     * 获取带有分页的【查找器】数据列表，
     * @returns {IterableIterator<{msg: string, data: (*|Array), status: *}|*>}
     */* findObjectList({ payload }, { call, put }) {
      const code = payload.finderCode;
      const response = yield call(findObjectList, omit(payload, ['finderCode']));
      if (typeof response != 'undefined' &&
        (200 === response.status || 1 === response.status)) {
        const dataList = response.data ? response.data.records : [];

        yield put({
          type: 'changeComboData',
          payload: {
            code,
            data: dataList,
          },
        });
        return {
          status: response.status,
          msg: '',
          data: dataList,
        };
      }
    },
    * findByIndustry({}, { call, put }) {
      const response = yield call(findIndustry);
      if (typeof response != 'undefined' && (200 == response.status || 1 == response.status)) {
        yield put({
          type: 'industryComboData',
          payload: response.data,
        });
      }
    },
    * findSolution({}, { call, put }) {
      const response = yield call(findSolution);
      if (typeof response != 'undefined' &&
        (200 === response.status || 1 === response.status)) {
        yield put({
          type: 'solutionComboData',
          payload: response.data,
        });
      }
    },
    * sendCaptcha({ payload }, { call, put }) {
      const response = yield call(sendCaptcha, payload);
      console.log('response:', response);
      if (typeof response != 'undefined' &&
        (200 === response.status || 1 === response.status)) {

      } else {

      }
    },

    * fileUpload({ payload }, { call, put }) {

    },
    * resetPassword({ payload }, { call, put }) {
      const response = yield call(resetPassword, payload);
      if (typeof response != 'undefined' && (200 == response.status || 1 == response.status)) {
        //yield put({
        //  type: 'solutionComboData',
        //  payload: response.data
        //});

        Modal.success({
          title: '修改密码成功:',
          content: (
            <div>
              <p>返回登录页面？</p>
            </div>
          ),
          okText:'好的',
          onOk() {
            router.push('/user/login');
          },
        });

      }
      if (typeof response != 'undefined' &&
        200!== response.status) {
        message.error(response.msg||"登录失败")
      }
    },
    // 登录成功之后，会触发这个 action ，以更新 state 的公用数据
    * afterLogin({payload}, { call, put }) {
      const userInfo = getStorage('userInfo');
      const accountInfo = getStorage('accountInfo');

      yield put({
        type: 'loginTimeout',
        payload: false
      });

      yield put({
        type: 'updateUserInfo',
        payload: userInfo,
      });
      yield put({
        type: 'setting/updateAccountInfo',
        payload: accountInfo,
      });
      // 获取当前用户信息
      yield put({
        type: 'findSelfInfo',
      });
    },
    * logout(_, { call, put }) {
      const response = yield call(logout);
      if (response || (!isLogin(response, false))) {
        removeStorage('userInfo');
        removeStorage('accountInfo');
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            //search: stringify({
            //    redirect: window.location.href
            //})
          }),
        );
      }
    },
    * findSelfInfo({ payload }, { call, put }) {
      // 获取用户信息
      const info = getUserInfo() || {};
      if (info.id) {
        const rsp = yield call(findUserInfo, { id: info.id });
        if ((200 === rsp.status || 1 === rsp.status) && rsp.data) {
          setStorage('userInfo', rsp.data);
          yield put({
            type: 'updateUserInfo',
            payload: rsp.data,
          });
        }
        return rsp;
      }
    },
    * findDocList({ payload }, { call, put }) {
      //console.log('effects....:');
      const response = yield call(findDocList, payload);
      const newPayload = {
        list: [],
      };
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        newPayload.list = response.data.records;
      }
      yield put({
        type: 'docList',
        payload: newPayload,
      });
      return response;
    },
    * renameDoc({ payload }, { call, put }) {
      const response = yield call(renameDoc, payload);
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        message.success('修改成功');
        yield put({
          type: 'findDocList',
        });
      }
      return response;
    },
    * deleteDoc({ payload }, { call, put }) {
      const response = yield call(deleteDoc, payload);
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        message.success('删除成功');
        yield put({
          type: 'findDocList',
        });
      }
      return response;
    },
    * createDoc({ payload }, { call, put }) {
      const response = yield call(createDoc, payload);
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        message.success('保存成功');
        yield put({
          type: 'findDocList',
        });
      }
      return response;
    },
    * uploadDoc({ payload }, { call, put }) {
      //console.log('payload:',payload);
      const response = yield call(uploadDoc, payload);
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        message.success('保存成功');
        yield put({
          type: 'findDocList',
        });
      }
      return response;
    },
    * batchDelDoc({ payload }, { call, put }) {
      //console.log('payload:',payload);
      const response = yield call(batchDelDoc, payload);
      if (isObject(response) && (200 === response.status || 1 === response.status)) {
        message.success('删除成功');
        yield put({
          type: 'findDocList',
        });
      }
      return response;
    },
  },
  reducers: {
    loginTimeout(state, {payload}) {
      return { ...state, loginTimeout: payload || false };
    },
    updateAppCode(state, { payload }) {
      return { ...state, appCode: payload.appCode || '' };
    },
    updateUserInfo(state, { payload }) {
      const { userInfo } = state;
      let newUserInfo;

      if (!isEmpty(payload)) {
        newUserInfo = { ...userInfo, ...payload };
      } else {
        newUserInfo = userInfo;
      }
      return {
        ...state, userInfo: newUserInfo,
      };
    },
    changeLayoutCollapsed(state, { payload }) {
      return {
        ...state,
        collapsed: payload,
        siderWidth: payload ? 80 : 200,
      };
    },
    changeComboData(state, { payload: { code, data } }) {
      const tmpO = {};
      tmpO[code] = isArray(data) ? orderBy(data, ['code'], ['asc']) : [];
      return { ...state, ...tmpO };
    },

    industryComboData(state, { payload }) {
      return { ...state, industry: payload };
    },
    solutionComboData(state, { payload }) {
      return { ...state, solution: payload };
    },
    docList(state, { payload }) {
      return { ...state, docList: payload.list };
    },
  },
};
